// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-11-19

package zipkin_plugin

import (
	"fmt"
	"gitee.com/go-libs/log/common"
	"sync"
)

// 上报插件.
type plugin struct {
	formatter common.SpanFormatter
	mu        *sync.RWMutex
	reporter  common.SpanReporter
}

// New
// 创建实例.
func New() common.SpanPlugin {
	return (&plugin{
		mu: &sync.RWMutex{},
	}).init()
}

func (o *plugin) GetFormatter() (formatter common.SpanFormatter) {
	o.mu.RLock()
	formatter = o.formatter
	o.mu.RUnlock()
	return
}

func (o *plugin) GetReporter() (reporter common.SpanReporter) {
	o.mu.RLock()
	reporter = o.reporter
	o.mu.RUnlock()
	return
}

func (o *plugin) Report(spans []common.Span) (err error) {
	if f := o.GetFormatter(); f != nil {
		err = o.reporter.Report(f, spans)
	} else {
		err = fmt.Errorf(`formatter not defined`)
	}
	return
}

func (o *plugin) SetFormatter(formatter common.SpanFormatter) {
	if formatter != nil {
		o.mu.Lock()
		o.formatter = formatter
		o.mu.Unlock()
	}
}

func (o *plugin) SetReporter(reporter common.SpanReporter) {
	if reporter != nil {
		o.mu.Lock()
		o.reporter = reporter
		o.mu.Unlock()
	}
}

// +------------------------------------------------------------------------------+
// | Access methods                                                               |
// +------------------------------------------------------------------------------+

func (o *plugin) init() *plugin {
	o.formatter = (&formatter{}).init()
	o.reporter = (&reporter{}).init()
	return o
}
